import React, { useEffect, useState } from "react";
import "@/styles/system/general.scss";
import { useNavigate, useParams } from "react-router-dom";
import { Button, Form, Input, Select, Space } from "antd";
import EditorTableComponent from "@/components/iteration/EditorTableComponent";
import "@/styles/tool/createTable.scss";
import { useForm } from "antd/es/form/Form";
import javaType from "@/config/javaType.json";

import { getGenTable, updateGenTable } from "@/api/tool/generate";
const inflection = require("inflection");

const HeaderComponent = ({ form }) => {
  const incrementTypeOptions = [
    { value: "", label: "-" },
    { value: "AUTO", label: "AUTO 数据库ID自增" },
    { value: "INPUT", label: "INPUT 插入前自行设置主键值" },
    { value: "ASSIGN_ID", label: "ASSIGN_ID 随机长整型" },
    { value: "ASSIGN_UUID", label: "ASSIGN_UUID 随机字符串" },
  ];

  const initialValues = {
    moduleName: "system",
    packageName: "com.randi.system",
  };

  return (
    <div className="header-card">
      <Form form={form} className="layout-form" colon={false} initialValues={initialValues}>
        <Form.Item name="tableName" label="表名" rules={[{ required: true, message: "请输入字段名" }]}>
          <Input placeholder="请输入表名" />
        </Form.Item>
        <Form.Item name="className" label="实体名称" rules={[{ required: true, message: "请输入实体名称" }]}>
          <Input placeholder="请输入实体名称" />
        </Form.Item>
        <Form.Item name="incrementType" label="主键策略">
          <Select showSearch options={incrementTypeOptions} />
        </Form.Item>
        <Form.Item name="tableComment" label="描述信息" rules={[{ required: true, message: "请输入描述信息" }]}>
          <Input placeholder="请输入描述信息" />
        </Form.Item>
        <Form.Item name="moduleName" label="模块名称" rules={[{ required: true, message: "请输入模块名称" }]}>
          <Input placeholder="请输入模块名称" />
        </Form.Item>
        <Form.Item name="businessName" label="业务名称" rules={[{ required: true, message: "请输入业务名称" }]}>
          <Input placeholder="请输入业务名称" />
        </Form.Item>
        <Form.Item name="functionName" label="功能名称" rules={[{ required: true, message: "请输入功能名称" }]}>
          <Input placeholder="请输入业务名称" />
        </Form.Item>
        <Form.Item name="packageName" label="生成路径" rules={[{ required: true, message: "请输入生成路径" }]}>
          <Input placeholder="请输入生成路径" />
        </Form.Item>
      </Form>
    </div>
  );
};

const TableComponent = ({ dataSource, loading, onChange, formList }) => {
  const htmlTypeOptions = [
    { value: "input", label: "文本框" },
    { value: "inputNumber", label: "数字框" },
    { value: "textArea", label: "文本域" },
    { value: "select", label: "下拉框" },
    { value: "checkbox", label: "复选框" },
    { value: "radio", label: "单选框" },
    { value: "datetime", label: "日期控件" },
    { value: "image", label: "图片上传控件" },
    { value: "upload", label: "文件上传控件" },
    { value: "editor", label: "富文本控件" },
  ];

  const queryTypeOptions = [
    { value: "EQ", label: "==" },
    { value: "NE", label: "!=" },
    { value: "GT", label: ">" },
    { value: "GTE", label: ">=" },
    { value: "LT", label: "<" },
    { value: "LTE", label: "<=" },
    { value: "LIKE", label: "LIKE" },
    { value: "BETWEEN", label: "BETWEEN" },
  ];

  const defaultColumns = [
    { title: "序号", align: "center", width: "54px", fixed: "left", render: (_, __, index) => index + 1 },
    { title: "字段名", dataIndex: "columnName", width: "140px" },
    { title: "类型", dataIndex: "columnType", width: "140px" },
    {
      title: "Java字段名",
      dataIndex: "javaField",
      width: "140px",
      component: "Input",
      rules: [{ required: true, message: "请输入字段名" }],
    },
    {
      title: "Java类型",
      dataIndex: "javaType",
      width: "120px",
      component: "Select",
      componentData: javaType,
    },
    {
      title: "必填",
      dataIndex: "isRequired",
      width: "54px",
      align: "center",
      component: "Checkbox",
      resType: "number",
      disabled: (_, record) => !!record.isPrimaryKey,
    },
    {
      title: "添加",
      dataIndex: "isInsert",
      width: "54px",
      align: "center",
      component: "Checkbox",
      resType: "number",
      disabled: (_, record) => !!record.isPrimaryKey,
    },
    {
      title: "修改",
      dataIndex: "isEdit",
      width: "54px",
      align: "center",
      component: "Checkbox",
      resType: "number",
      disabled: (_, record) => !!record.isPrimaryKey,
    },
    {
      title: "列表",
      dataIndex: "isList",
      width: "54px",
      align: "center",
      component: "Checkbox",
      resType: "number",
    },
    {
      title: "查询",
      dataIndex: "isQuery",
      width: "54px",
      align: "center",
      component: "Checkbox",
      resType: "number",
    },
    {
      title: "查询方式",
      dataIndex: "queryType",
      width: "100px",
      component: "Select",
      componentData: queryTypeOptions,
    },
    {
      title: "显示类型",
      dataIndex: "htmlType",
      width: "150px",
      component: "Select",
      componentData: htmlTypeOptions,
    },
    { title: "描述", dataIndex: "columnComment", component: "Input" },
  ];

  return (
    <EditorTableComponent
      className="editor-table"
      isOptions="false"
      size="middle"
      tableLayout="auto"
      bordered={true}
      dataSource={dataSource}
      defaultColumns={defaultColumns}
      loading={loading}
      onChange={onChange}
      formList={formList}
    />
  );
};

const CreateComponent = () => {
  const navigate = useNavigate();
  const [form] = useForm();
  const [tableDataSource, setTableDataSource] = useState([]);
  const [loading, setLoading] = useState(false);
  const formList = new Set();

  const { id: tableId } = useParams();

  useEffect(() => {
    setLoading(true);
    getGenTable(tableId)
      .then((res) => {
        const columns = res.columns;
        Reflect.deleteProperty(res, "columns");
        form.setFieldsValue(res);
        setTimeout(() => {
          setLoading(false);
          setTableDataSource(columns);
        }, 500);
      })
      .catch(() => setLoading(false));
  }, [tableId, form]);

  const onFinish = async () => {
    // 校验所有表单
    const promiseList = [...formList, form].map((form) => form.validateFields());
    await Promise.all(promiseList);

    // 获取获取头部数据，合并数据
    const value = form.getFieldsValue();
    value.columns = tableDataSource;
    value.tableId = tableId;

    await updateGenTable(value);
    navigate("/tool/generate");
  };

  const onAutoFill = async () => {
    // 获取头部表达值
    const values = form.getFieldsValue();
    // 实体名称
    if (values.tableName && !values.className) {
      form.setFieldsValue({ className: inflection.camelize(values.tableName) });
    }
    // 业务名称
    if (values.tableName && !values.businessName) {
      form.setFieldsValue({ businessName: values.tableName.split("_").pop() });
    }

    // 模块名称
    if (values.tableComment && !values.functionName) {
      form.setFieldsValue({ functionName: values.tableComment.replace("表", "") });
    }

    // 表格数据处理
    const data = tableDataSource.map((item) => {
      item.javaField = item.javaField || inflection.camelize(item.columnName, true);
      if (item.columnType.includes("bigint")) {
        item.javaType = item.javaType || "Long";
        item.htmlType = item.htmlType || "inputNumber";
      } else if (item.columnType.includes("int")) {
        item.javaType = item.javaType || "Integer";
        item.htmlType = item.htmlType || "inputNumber";
      } else if (item.columnType.includes("varchar")) {
        item.javaType = item.javaType || "String";
        item.htmlType = item.htmlType || "input";
      } else if (item.columnType.includes("datetime")) {
        item.javaType = item.javaType || "Date";
        item.htmlType = item.htmlType || "datetime";
      } else if (item.columnType.includes("decimal")) {
        item.javaType = item.javaType || "BigDecimal";
        item.htmlType = item.htmlType || "input";
      }
      if (item.isRequired) {
        item.isInsert = item.isInsert || 1;
        item.isEdit = item.isEdit || 1;
      }
      return item;
    });
    await setTableDataSource(data);
    Promise.all([...formList].map((form) => form.validateFields()));
  };

  return (
    <div className="genConfig-wrpper">
      <HeaderComponent form={form} />

      <div className="main-card table-card">
        <TableComponent
          dataSource={tableDataSource}
          loading={loading}
          onChange={(data) => setTableDataSource(data)}
          formList={formList}
        />
      </div>
      <div className="buttom-card">
        <Space>
          <Button onClick={() => navigate("/tool/generate")}>取消</Button>
          <Button type="primary" onClick={onFinish}>
            保存
          </Button>
          <Button type="link" onClick={onAutoFill}>
            一键填值
          </Button>
        </Space>
      </div>
    </div>
  );
};
export default CreateComponent;
